package org.hbrs.ooka.model.persistence;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.hbrs.ooka.model.Product;

public class ProductDatabaseDAO implements ProductDAO {

	private DatabaseSource m_databaseSource;


	public ProductDatabaseDAO(DatabaseSource dbs) {
		this.m_databaseSource = dbs;
	}
	
	@Override
	public Product findByID(Integer id) {
		ResultSet rs = this.m_databaseSource.executeQuery("select * from product where id=" + id);
		String bezeichnung = "";
		Product prod = null;
		try {
			while(rs.next()){
				bezeichnung = rs.getString("bezeichnung");
				if(bezeichnung != null){
					prod = new Product(bezeichnung);
					prod.setId(id);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.m_databaseSource.closeResultSet(rs);
		}
		return prod;
	}

	@Override
	public int insert(Product p) {
		System.out.println("Inserting product: " + p.toString());
		int id = 0;
		if((id = this.isInDatabase(p)) == 0){
			this.m_databaseSource.execute("insert into product values(" + p.getId() + ", \"" + p.getBeschreibung() + "\")");
		} else {
			p.setId(id);
		}
		return p.getId();
	}

	
	private int isInDatabase(Product p){
		ResultSet rs = this.m_databaseSource.executeQuery("select * from product where id = " + p.getId() + " or bezeichnung = \"" + p.getBeschreibung()  + "\"");
		int id = 0;
		
		try {
			while(rs.next()){
				id = rs.getInt("id");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			this.m_databaseSource.closeResultSet(rs);
		}
		return id;
	}
}
